import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;


public class Decoder {
	
	private HuffmanTree ht = new HuffmanTree();

	public void decodeFile(String origFile,String destFile){
		String str = decode( origFile );
		writeDecodedFile(destFile, str);
	}
	
	private String decode(String fileName)
	{
		String str = new String();
		try(FileInputStream fis = new FileInputStream(fileName)) {
			BitSequence bs = new BitSequence();
			int b = 0;
			while( (b = fis.read()) != -1 ){
				bs.addLast( (char) b );
			}
			str = ht.decode(bs);
			fis.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e)	{
			e.printStackTrace();
		}
		return str;
	}	
	
	public void writeDecodedFile(String fileDest, String str)
	{
		try (FileOutputStream fot = new FileOutputStream(fileDest)) {
			BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fot));
			out.write(str);
			out.flush();
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e)	{
			e.printStackTrace();
		}
	}
}
